﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pers.mine.utils;
using System.Threading;
using DMSkin.Metro.Controls;
using System.IO;

namespace X_File
{
    public partial class MainForm : DMSkin.DMSkinForm
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Animate.AnimateWindow(this.Handle, 300, Animate.AW_VER_POSITIVE);//滑动进入
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            //Graphics g = e.Graphics;//获取绘制对象
            /////设置参数
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            //// Create pen.
            //Pen pen = new Pen(Color.Gainsboro, 3);

            //// Create points that define line.
            //Point point1 = new Point(0, 55);
            //Point point2 = new Point(500, 55);
            //g.DrawLine(pen, point1, point2);
        }
        private void tabPage1_Click(object sender, EventArgs e)
        {
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Animate.AnimateWindow(this.Handle, 300, Animate.AW_HIDE + Animate.AW_VER_NEGATIVE);//滑动退出
        }

        private void metroButtonStart_Click(object sender, EventArgs e)
        {
            
            //获取配置信息
            long partSize = 0;
            Int16 type = 0;
            String source = "";
            String targetPath = "";
            MetroRadioButton typeBtn = getCkeckedMetroRadioButton(panelSplitType);
            MetroRadioButton sizeBtn = getCkeckedMetroRadioButton(panelSplitSize);
            if (typeBtn != null)
            {
                type = Convert.ToInt16(typeBtn.Tag.ToString());
            }
            if (sizeBtn != null)
            {
                if ("other".Equals(sizeBtn.Tag))
                {
                    if (dmTextBoxOther.Text.Length < 1)
                    {
                        newLineLog("截取大小未指定...");
                        dmTextBoxOther.Focus();
                        return;
                    }
                    partSize = Convert.ToInt64(dmTextBoxOther.Text) * (1<<10);
                }
                else
                {
                    partSize = Convert.ToInt64(sizeBtn.Tag.ToString());
                }

            }
            source = dmTextBoxSourceFile.Text;
            targetPath = dmTextBoxTargetPath.Text;
            if (String.IsNullOrWhiteSpace(source))
            {
                newLineLog("源文件未指定...");
                dmTextBoxSourceFile.Focus();
                return;
            }
            this.metroButtonStart.Enabled = false;
            this.metroButtonStart.Text = "处理中...";
            FilePartCopy fpc = new FilePartCopy();
            fpc.source = source;
            fpc.targetPath = targetPath;
            fpc.partSize = partSize;
            fpc.copyType = type;
            fpc.startEvent += new EventHandler(pcp_StartEvent);
            fpc.processEvent += new EventHandler(pcp_ProcessEvent);
            fpc.partStartEvent += new EventHandler(pcp_PartStartEvent);
            fpc.endEvent += new EventHandler(pcp_EndEvent);
            Thread thread = new Thread(new ThreadStart(fpc.ExecuteCopy));
            thread.Start();
        }

        private MetroRadioButton getCkeckedMetroRadioButton(Panel pan)
        {
            MetroRadioButton mrb = null;
            var cs = pan.Controls;
            foreach (var item in cs)
            {
                if (item is MetroRadioButton)
                {
                    mrb = item as MetroRadioButton;
                    if (mrb.Checked)
                    {
                        return mrb;
                    }
                }
            }
            return null;
        }
        //线程调用的委托  
        private delegate void fcpDelegate(FilePartCopy fps);

        /// <summary>  
        /// 线程开始事件,设置进度条最大值  
        /// 但是我不能直接操作进度条,需要一个委托来替我完成  
        /// </summary>  

        void pcp_StartEvent(object sender, EventArgs e)
        {
            FilePartCopy fpc = sender as FilePartCopy;
            //匿名委托
            fcpDelegate sd = delegate(FilePartCopy fps)
            {
                
                this.progressBar.Value = 0;
                newLineLog("任务信息:");
                newLineLog(" 待处理文件长度:" + fpc.sourceLength / (1 << 20) + "M");
                newLineLog(" 截取部分大小:" + fpc.partSize / (1 << 20) + "M");
                newLineLog(" 目标文件个数:" + fpc.partCount);

            };
            this.Invoke(sd, fpc);
        }

        void pcp_ProcessEvent(object sender, EventArgs e)
        {
            FilePartCopy fpc = sender as FilePartCopy;
            //使用Lambda表达式来创建委托对象
            fcpDelegate now = filePc =>
            {
                Double progress = Math.Round(Convert.ToDouble(filePc.curCopyLength) / Convert.ToDouble(filePc.partSize * filePc.partCount), 2);
                if (progress > 1)
                {
                    progress = 1;
                }
                this.progressBar.Value = (int)(progress * 100);
            };
            this.Invoke(now, fpc);
        }
        void pcp_PartStartEvent(object sender, EventArgs e)
        {
            FilePartCopy fpc = sender as FilePartCopy;
            fcpDelegate now = filePc =>
            {
                newLineLog("正在处理第[" + fpc.curCopyPart + "]部分...");
            };
            this.Invoke(now, fpc);
        }
        void pcp_EndEvent(object sender, EventArgs e)
        {
            FilePartCopy fpc = sender as FilePartCopy;
            //使用Lambda表达式来创建委托对象
            fcpDelegate now = filePartCopy =>
            {
                this.progressBar.Value = 100;
                if (filePartCopy.errmsgs == null || filePartCopy.errmsgs.Count < 1)
                {
                    newLineLog("任务已完成^_^");
                }
                else
                {
                    foreach (var item in filePartCopy.errmsgs)
                    {
                        newLineLog(item);
                        newLineLog("任务已结束.");
                    }
                }
                this.metroButtonStart.Text = "开始";
                this.metroButtonStart.Enabled = true;
            };
            this.Invoke(now, fpc);
        }

        private void newLineLog(String msg)
        {
            String appPrefix = System.Environment.NewLine;
            if (msg == null)
            {
                msg = "";
            }
            if (String.IsNullOrWhiteSpace(dmTextBoxLog.Text))
            {
                dmTextBoxLog.Text = "";
                appPrefix = "";
            }
            if (dmTextBoxLog.Text.Length + msg.Length > dmTextBoxLog.MaxLength)
            {
                dmTextBoxLog.Text = "_(:3」∠)_";
            }
            dmTextBoxLog.AppendText(appPrefix + msg);

        }

        private void dmTextBoxOther_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar)) { e.Handled = true; }

        }

        private void metroButtonSoucres_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.ShowDialog();
            if (!String.IsNullOrEmpty(file.FileName))
            {
                this.dmTextBoxSourceFile.Text = file.FileName;
            }
            dmTextBoxSourceFile.Focus();
            dmTextBoxSourceFile.Select(0,0);
        }

        private void metroButtonTargetPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            if(!String.IsNullOrEmpty(path.SelectedPath)){
                this.dmTextBoxTargetPath.Text = path.SelectedPath;
            }
            dmTextBoxTargetPath.Focus();
            dmTextBoxTargetPath.Select(0, 0);
        }

        private void dmTextBoxSourceFile_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (var item in files)
            {
                if (File.Exists(item))
                {
                    dmTextBoxSourceFile.Text = item;
                    break;
                }
            }
        }

        private void dmTextBoxSourceFile_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void dmTextBoxTargetPath_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (files.Length > 0)
            {
                if (File.Exists(files[0])) {
                    dmTextBoxTargetPath.Text = Path.GetDirectoryName(files[0]);
                }
                else if (Directory.Exists(files[0]))
                {
                    dmTextBoxTargetPath.Text = files[0];
                }
            }
        }

        private void dmTextBoxTargetPath_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void MainForm_Activated(object sender, EventArgs e)
        {
            dmTabControl.SelectedIndex = dmTabControl.SelectedIndex;
        }
    }
}
